//
//  EXRefreshView.m
//  Exercise
//
//  Created by 羊谦 on 16/6/20.
//  Copyright © 2016年 NetEase-yangqian. All rights reserved.
//

#import "EXRefreshView.h"

@interface EXRefreshView ()

@property (nonatomic,strong) UIImageView *arroView;//箭头
@property (nonatomic,strong) UILabel *tipLabel;//刷新文字
@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic, assign) id target;
@property (nonatomic, assign) SEL action;

@end

@implementation EXRefreshView
{
@private
    BOOL _rotationFlag;//是否需要改变箭头方向
    BOOL _isLoading;//是否正在加载
    BOOL _isFirstEnter;
    CGFloat _defaultContentOffset;//初始偏移距离
}


- (instancetype)initWithTableview:(UITableView *)tableView target:(id)target action:(SEL)action {
    self = [super initWithFrame:CGRectZero];
    if (self) {
        self.target = target;
        self.action = action;
        self.backgroundColor = [UIColor whiteColor];
        _tableView = tableView;
        _isFirstEnter = YES;
        [self setUpView];
        [_tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];
        [_tableView addObserver:self forKeyPath:@"decelerating" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}


-(void)dealloc {
    [_tableView removeObserver:self forKeyPath:@"contentOffset"];
    [_tableView removeObserver:self forKeyPath:@"decelerating"];
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    CGFloat Y = _tableView.contentOffset.y;
    if (_isFirstEnter) {
        _isFirstEnter = NO;
        _defaultContentOffset = Y;
    }
    //    NSLog([NSString stringWithFormat:@"%f",Y]);
    if (Y>=0 || Y == _defaultContentOffset) {
        return;
    }
    if (Y-_defaultContentOffset<=-36 && !_rotationFlag) {
        _rotationFlag = YES;
        [self rotationRefresh:_rotationFlag];
    }else if (Y-_defaultContentOffset>-36 && _rotationFlag) {
        _rotationFlag = NO;
        [self rotationRefresh:_rotationFlag];
    }
    if (_tableView.decelerating && Y-_defaultContentOffset <= -30 ) {
        [self beginLoadingAnimator];
    }
}

- (void)setUpView {
    self.arroView = [UIImageView new];
    self.arroView.image = [UIImage imageNamed:@"tableview_pull_refresh"];
    [self addSubview:self.arroView];
    [self.arroView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self).offset(-40);
        make.centerY.mas_equalTo(self);
        make.width.and.height.mas_equalTo(25);
    }];
    
    self.tipLabel = [UILabel new];
    self.tipLabel.font = [UIFont systemFontOfSize:13];
    self.tipLabel.textColor = [UIColor lightGrayColor];
    self.tipLabel.text = @"下拉刷新";
    [self addSubview:self.tipLabel];
    [self.tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.arroView.mas_right).offset(15);
        make.centerY.mas_equalTo(self.arroView);
    }];
}

/**
 *  旋转箭头 改变文字
 *
 *  @param flag
 */
- (void)rotationRefresh:(BOOL)flag {
    if (_isLoading) {
        return;
    }
    CGFloat angle = flag ? -0.01 : 0.01;
    [UIView animateWithDuration: 0.2 animations:^{
        self.arroView.transform = CGAffineTransformRotate(self.arroView.transform, angle + M_PI);
        self.tipLabel.text = flag ? @"释放刷新" : @"下拉刷新";
    } completion: ^(BOOL finished) {
        
    }];
}

//开始菊花
- (void)beginLoadingAnimator {
    [_tableView setContentOffset:CGPointMake(0, _defaultContentOffset+(-36)) animated:YES];
    if (_isLoading) {
        return;
    }
    self.tipLabel.text = @"正在加载...";
    self.arroView.image = [UIImage imageNamed:@"tableview_loading"];
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
    anim.repeatCount = MAXFLOAT;
    anim.duration = 0.35;
    anim.toValue = [NSNumber numberWithDouble:2*M_PI];
    // 默认removedOnCompletion后就会移除动画
    anim.removedOnCompletion = false;
    [self.arroView.layer addAnimation:anim forKey:@"tranform"];
    _isLoading = YES;
    [self.target performSelector:self.action withObject:self afterDelay:0.0];
}

- (void)endRefresh {
    _isLoading = NO;
    _rotationFlag = NO;
    [UIView animateWithDuration: 0.3 animations:^{
        [self.tableView setContentOffset:CGPointMake(0, -_defaultContentOffset) animated:NO];
    } completion:^(BOOL finished) {
        [self.arroView.layer removeAnimationForKey:@"tranform"];
        self.arroView.image = [UIImage imageNamed:@"tableview_pull_refresh"];
        self.arroView.transform = CGAffineTransformRotate(self.arroView.transform, 0.01 + M_PI);
        self.tipLabel.text = @"下拉刷新";
    }];
}

-(void)layoutSubviews {
    [super layoutSubviews];
    self.frame = CGRectMake(self.superview.frame.origin.x/2.0, -40,self.superview.width, 40);
}
@end